<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<video id="recplayer" autoplay>start record</video>
<button id="record">start record</button>
<button id="stopRecord">stop record</button>
<button id="replay">play</button>
<button id="download">download</button>
<div id="divConstraints">Constraints</div>
<script>
  var buffer = [];
  var mediaRecorder;
  const $divConstraints = document.querySelector('#divConstraints');
  const $recplayer = document.querySelector('#recplayer');
  const $record = document.querySelector('#record');
  const $stopRecord = document.querySelector('#stopRecord');
  const $replay = document.querySelector('#replay');
  const $download = document.querySelector('#download');

  function start() {
    if(!navigator.mediaDevices ||
      !navigator.mediaDevices.getUserMedia){

      console.log('getUserMedia is not supported!');
      return;

    }else{

      var constraints = {
        video : {
          width: 640,
          height: 480,
        },
        audio : true
      }

      navigator.mediaDevices.getUserMedia(constraints)
        .then(gotMediaStream)
        // .then(startRecord)
    }
  }

  start();

  function handleDataAvailable (ev) {
    if (ev && ev.data && ev.data.size > 0) {
      buffer.push(ev.data)
    }
  }

  function gotMediaStream(stream) {
    var videoTrack = stream.getVideoTracks()[0];
    var videoConstraints = videoTrack.getSettings();

    $divConstraints.textContent = `
    ${ JSON.stringify(videoConstraints, null, 2) }
    `;

    window.stream = stream;
    $recplayer.srcObject = stream;
  }

  function startRecord () {
    var options = {
      mimeType: 'video/webm;codecs=vp8',
    };

    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
      console.error(`${ options.mimeType } is not supported!`);
      return
    }

    try {
      mediaRecorder = new MediaRecorder(window.stream, options)
    } catch (error) {
      console.error(`Failed to create MediaRecorder:`, error);
    }

    // 当数据有效时，会调用此方法，可以用来存储数据
    // 每次记录一定时间的数据，指定时间时，会定期触发，没有会结束时触发。
    mediaRecorder.ondataavailable = handleDataAvailable;

    // 10： 时间片，每隔这个时间，储存一次数据
    mediaRecorder.start(10);
  }

  function stopRecord () {
    mediaRecorder.stop()
  }

  function download () {
    var a = document.createElement('a')
    var blob = new Blob(buffer, { type: 'video/webm' })
    a.href = window.URL.createObjectURL(blob);

    a.style.display = 'none'
    a.download = 'video-name.webm'
    a.click()
  }

  function startReplayer () {
    var blob = new Blob(buffer, { type: 'video/webm' });
    $recplayer.src = window.URL.createObjectURL(blob);
    $recplayer.srcObject = null;
    $recplayer.controls = true;
    $recplayer.play();
  }

  $record.onclick = startRecord
  $stopRecord.onclick = stopRecord

  $replay.onclick = startReplayer

  $download.onclick = download
</script>
</body>
</html>
